Saving State

N. Springer

https://lh6.googleusercontent.com/QSSZdFq8C9xR6iM4nBf7mgmobgT2vBbJfMJtvgrV0qFqe7_1J-ohizEiu9R7_E5cZZZ5WwFx35xXxO5m3HVXI3yr1pGd7nhRRyEH5HKkjbu8ipuJ_QA-yYj-siG-H2OrhzvxGWNl

 

Android will automatically save the state of the program until it is destroyed (press square by home button then swipe program to side). This tutorial teaches how to save state after the program is closed by storing information in text files.

  1. In your main java file, create two methods: onStop(), and onStart(). These functions are run when the program stops and starts

 

protected void onStop() {

  super.onStop();

}

 

protected void onStart() {

  super.onStart();

}

 

2. Use the things you learned in T04 in order to create input and output readers to the internal storage

 

3. In the onStop() function, use the writer to write the information you need to store onto a text file. The pieces of data must be separated by a certain character. In this example, I write strings that are used in a calculator program, separated by commas:

//display,operator,stored,current

writer.write(display.getText().toString() + "," + operator + "," + stored + "," + current);

 

4. In order to read this file, use the reader to read the line and save it, then use the String.split(char) function to split the string based on the character you used to separate your pieces of data. Then you can go through the array of strings generated by the split function, and you can find your data.

 

String str = reader.readLine();

reader.close();

String[] strings = str.split(",");

//display,operator,stored,current

display.setText(strings[0]);

operator = strings[1];

opDisplay.setText(operator);

stored = strings[2];

current = strings[3];

 

Using this method, your program state won’t be lost even if the you close it or restart your device.